const app = getApp()
const netRequest = require("../../utils/requestUtil.js");

Page({
  data: {
    motto: 'Hello World',
    userInfo: {},
    hasUserInfo: false,
    canIUse: wx.canIUse('button.open-type.getUserInfo')
  },
  //事件处理函数
  bindViewTap: function () {
    wx.showToast({
      title: '暂未开放',
      image: '/images/moon.png',
      duration: 2000
    });


    this.testUserLogin();
  },
  onLoad: function () {
   

    
    if (app.globalData.userInfo) {
      this.setData({
        userInfo: app.globalData.userInfo,
        hasUserInfo: true
      })
    } else if (this.data.canIUse) {
      // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
      // 所以此处加入 callback 以防止这种情况
      app.userInfoReadyCallback = res => {
        this.setData({
          userInfo: res.userInfo,
          hasUserInfo: true
        })
      }
    } else {
      // 在没有 open-type=getUserInfo 版本的兼容处理
      wx.getUserInfo({
        success: res => {
          app.globalData.userInfo = res.userInfo
          this.setData({
            userInfo: res.userInfo,
            hasUserInfo: true
          })
        }
      })
    }


    var items = [
      { title: "我的", img: "/images/present.png" },
      { title: "我的信息", img: "/images/add.png" },
      { title: "我的团队", img: "/images/sun_hl.png" },
      { title: "我的客户", img: "/images/time_hl.png" }
    ];


    this.setData({ items: items });
  },
  getUserInfo: function (e) {
    console.log(e)
    app.globalData.userInfo = e.detail.userInfo
    this.setData({
      userInfo: e.detail.userInfo,
      hasUserInfo: true
    })
  },



  testUserLogin:function(){
    var that = this;
    wx.getUserInfo({
      success: res => {    
        // 登录
        wx.login({
          success: loginRes => {
            // 发送 res.code 到后台换取 openId, sessionKey, unionId
            netRequest({
              url: "/user/loginByWxMini",
              data: { "code": loginRes.code, "encryptedData": res.encryptedData, "iv": res.iv, "rawData": res.rawData, "signature": res.signature },
              success: function (res) { console.log(res); },
              fail: function () { },
              complete: function () { }
            });
          }
        })
      }
    })
  }
})
